/*
 ============================================================================
 Name        : phase_aud.c
 Author      : chenf
 Version     : 1.0
 Copyright   : loongsec
 Description : add phase in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"

int new_channel(PARAM channelIndex, PARAM phaseIndex);
int update_channel(PARAM channelIndex, PARAM phaseIndex);
int clear_channel(PARAM phaseIndex);

sqlite3 *db = NULL;
int  nrow=0,ncolumn=0;
char **azResult = NULL;
char *zErrMsg =0;
char sql[1000];

int main(void) {
        char *input;
        char *req_method;
        int  rc;

        if(isvalid_cookie()!=0){
            return 0;
        }

        rc = sqlite3_open(PATH_DATABASE,&db);

        printf("Content-type:text/json;charset=utf-8\n\n");

        if (rc) {
            fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
            sqlite3_close(db);
            return 0;

        } else {
            req_method = getenv("REQUEST_METHOD");

            FILE* fp = (FILE*) stdin;
            input = getcgidata(fp, req_method);

            //PARAM un = getParam(input, "username");
            //printf("Your find is %s = %s  \n", un.key, un.value );

            //printf("Your input is %s<br>  \n", input );
            PARAM method  = getParam(input, "method");

            PARAM phase_index           = getParam(input, "phaseIndex");
            PARAM pedestrian_green_time = getParam(input, "pedestrianGreenTime");
            PARAM pedestrian_clear_time = getParam(input, "pedestrianClearTime");
            PARAM min_green_time        = getParam(input, "minGreenTime");
            PARAM unit_green_delay_time = getParam(input, "unitGreenDelayTime");
            PARAM max_green_time1       = getParam(input, "maxGreenTime1");
            PARAM max_green_time2       = getParam(input, "maxGreenTime2");
            PARAM flex_phase_fixed_green_time = getParam(input, "flexPhaseFixedGreenTime");
            PARAM green_flash_time      = getParam(input, "greenFlashTime");
            PARAM phase_type            = getParam(input, "phaseType");
            PARAM phase_option          = getParam(input, "phaseOption");
            PARAM extend                = getParam(input, "extend");
            
            PARAM channel               = getParam(input, "channel");

            char last_modified[]          = {"datetime(CURRENT_TIMESTAMP,'localtime')"};


            if( strcmp(method.value, "add") ==0 ){
                sprintf(sql, "INSERT INTO [tb_phase_parm] (\
                [phase_index],     [pedestrian_green_time],         [pedestrian_clear_time], \
                [min_green_time],  [unit_green_delay_time],         [max_green_time1], \
                [max_green_time2], [flex_phase_fixed_green_time],   [green_flash_time],\
                [phase_type],      [phase_option],                  [extend], [last_modified]) \
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %.0f, %s, %s, %s, %s);",
                phase_index.value,
                pedestrian_green_time.value,
                pedestrian_clear_time.value,
                min_green_time.value,
                unit_green_delay_time.value,
                max_green_time1.value,
                max_green_time2.value,
                flex_phase_fixed_green_time.value,
                atof(green_flash_time.value) * 10,
                phase_type.value,
                phase_option.value,
                extend.value,
                last_modified);

            } else if( strcmp(method.value, "update") ==0 ){
                sprintf(sql, "UPDATE [tb_phase_parm]  \
                set [pedestrian_green_time]  = %s,\
                  [pedestrian_clear_time]  = %s,\
                  [min_green_time]         = %s,\
                  [unit_green_delay_time]  = %s,\
                  [max_green_time1]        = %s,\
                  [max_green_time2]        = %s,\
                  [flex_phase_fixed_green_time]  = %s,\
                  [green_flash_time]       = %.0f,\
                  [phase_type]             = %s,\
                  [phase_option]           = %s,\
                  [extend]                 = %s,\
                  [last_modified]          = %s \
                WHERE [phase_index]          = %s ;",
                pedestrian_green_time.value,
                pedestrian_clear_time.value,
                min_green_time.value,
                unit_green_delay_time.value,
                max_green_time1.value,
                max_green_time2.value,
                flex_phase_fixed_green_time.value,
                atof(green_flash_time.value) * 10,
                phase_type.value,
                phase_option.value,
                extend.value,
                last_modified,
                phase_index.value);

            } else if( strcmp(method.value, "delete") ==0 ){
                sprintf(sql, " DELETE FROM [tb_phase_parm]  \
                WHERE [phase_index]          = %s ;",
                phase_index.value);

            }
            //printf("SQL: %s", sql);

            int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
            
            // asociate channel init
            PARAM channel_index[50];
            int si = getParams(input, "phase_channel_id", channel_index);
            int t = 0;
            int r = clear_channel(phase_index);
            for(t=0; t<si; t++){
                if( has_channel(channel_index[t]) == 0 ){
                    r = update_channel(channel_index[t], phase_index);
                } else {
                    r = new_channel(channel_index[t], phase_index);
                }
            }
           
            printf("{\"res\":\"%d\",\"msg\":\"%s\"}", sr + r, sqlite3_errmsg(db));

            sqlite3_close(db);//关闭数据库
            return 0;

        }
        //fflush(stdout);

    return EXIT_SUCCESS;
}


int has_channel(PARAM channelIndex){
    sprintf(sql, "select * from [tb_channel_parm] where channel_index = %s ", channelIndex.value);
    int rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr,"SQL error:%s\n", zErrMsg);
        sqlite3_close(db);
        return 0;

    }
    if (*azResult != NULL) {
        if(nrow >= 1){
            return 0;
        }else{
            return 1;
        }
    }
    return 1;
}

int clear_channel(PARAM phaseIndex){
    sprintf(sql, " UPDATE [TB_CHANNEL_PARM] \
                set [channel_ctrl_signal_source] = 0, \
                    [last_modified] = datetime(CURRENT_TIMESTAMP,'localtime') \
                WHERE [channel_ctrl_signal_source] = %s ;", phaseIndex.value);
    //printf("sql: %s\n", sql);
    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    return sr;
}

int update_channel(PARAM channelIndex, PARAM phaseIndex){
    sprintf(sql, " UPDATE [TB_CHANNEL_PARM] \
                set [channel_ctrl_signal_source] = %s, \
                    [last_modified] = datetime(CURRENT_TIMESTAMP,'localtime') \
                WHERE [channel_index] = %s ;", phaseIndex.value, channelIndex.value);
    //printf("sql: %s\n", sql);
    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    return sr;
}

int new_channel(PARAM channelIndex, PARAM phaseIndex){
    sprintf(sql, "INSERT INTO [TB_CHANNEL_PARM] (\
                [channel_index],\
                [channel_ctrl_signal_source],\
                [automatic_flash_channel_state], \
                [channel_ctrl_type], \
                [last_modified] ) \
                VALUES (%s, %s, 0, 0, datetime(CURRENT_TIMESTAMP,'localtime') );",
                channelIndex.value, phaseIndex.value);
    //printf("sql: %s\n", sql);
    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    return sr;
}
